<template>
    <el-card shadow="never">
        <!-- 头部插槽，放入面包屑 -->
        <div slot="header">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }"> <i class="el-icon-house"></i> 首页</el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <!-- 主体内容 -->
        <!-- 筛选区域 -->
        <div class="filter-bar">
            <!-- 筛选表单 -->
            <div class="l-form">
                <el-input size="small" placeholder="请输入内容" v-model="query" clearable @clear="resetQuery">
                    <template slot="append"> <i @click="searchQuery" class="el-icon-search"></i> </template>
                </el-input>
            </div>
            <!-- 右侧按钮 -->
            <div class="r-btn">
                <el-button type="primary" @click="addDialogShow=true" size="small" icon="el-icon-plus">增加</el-button>
            </div>
        </div>
        <!-- 表格区域 -->
        <div class="table-box">
            <!-- 表格 -->
            <el-table :data="userlist" border>
                <el-table-column label="用户名" align="center" prop="username"></el-table-column>
                <el-table-column label="邮箱" align="center" prop="email"></el-table-column>
                <el-table-column label="角色名" align="center" prop="role_name"></el-table-column>
                <el-table-column label="手机号" align="center" prop="mobile"></el-table-column>
                <el-table-column label="状态" width="100" align="center" prop="mg_state">
                    <template slot-scope="scope">
                        <!-- {{scope.row}} 就表示这一行的数据信息 -->
                        <el-switch @change="changeStatus(scope.row.id,$event)" v-model="scope.row.mg_state">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="注册时间" align="center" prop="create_time">
                    <template slot-scope="scope">
                      {{ scope.row.create_time | formateTime("YYYY/MM/DD") }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" >
                    <template slot-scope="scope">
                        <el-tooltip  effect="dark" content="修改" placement="top">
                            <el-button 
                                type="success" 
                                size="small" 
                                @click="editUser(scope.row.id)" 
                                circle 
                                icon="el-icon-edit" 
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip  effect="dark" content="删除" placement="top">
                            <el-button 
                                type="danger" 
                                size="small"  
                                @click="delUser(scope.row.id)"  
                                circle 
                                icon="el-icon-delete"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip  effect="dark" content="删除" placement="top">
                            <el-button 
                                type="warning" 
                                size="small"  
                                @click="setUserRole(scope.row)"  
                                circle 
                                icon="el-icon-setting"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            
            <!-- 分页器 -->
            <el-pagination
                background
                layout="sizes,prev, pager, next,jumper,->,total"
                :page-sizes="[1,2,3,4,5,6]"
                :current-page="pagenum"
                :page-size="pagesize"
                @size-change="sizeChange"
                @current-change="pageChange"
                :total="total">
            </el-pagination>
        </div>

        <!-- 增加表单弹框 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addDialogShow"
            width="40%"
        >
            <el-form  :model="addUserForm" ref="addUserForm" :rules="addUserFormRules" label-width="80px" size="normal">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addUserSubmit">立即创建</el-button>
                    <el-button @click="resetUserForm('addUserForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 修改表单弹框 -->
        <el-dialog
            title="修改用户"
            :visible.sync="editDialogShow"
            width="40%"
        >
            <el-form  :model="editUserForm" ref="editUserForm" :rules="editUserFormRules" label-width="80px" size="normal">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editUserForm.mobile"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="editUserSubmit">立即修改</el-button>
                    <el-button @click="resetUserForm('editUserForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 用户授权弹框 -->
        <el-dialog
            title="用户授权"
            :visible.sync="setRoleShow"
            width="40%"
            @close="rid=''"
           >
           <p>用户昵称：{{userInfo.username}}</p>
           <br>
           <p>当前角色：{{userInfo.role_name}}</p>
           <br>
           <p>授权角色：  
                <el-select v-model="rid" placeholder="请选择">
                    <el-option value=""  label="请选择" > </el-option>
                    <el-option v-for="item in rolelist" :key="item.id" :label="item.roleName" :value="item.id" > </el-option>
                </el-select>
             </p>
            <span slot="footer">
                <el-button @click="setRoleShow = false">Cancel</el-button>
                <el-button type="primary" @click="setRoleSubmit">OK</el-button>
            </span>
        </el-dialog>

    </el-card>
</template>
<script>
    // 表单自定义校验函数
    let validateEmail = (rules,value,cb)=>{
        if(value){
            let reg =  /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/
            if(reg.test(value)){
                cb()
            }else{
                cb(new Error("邮箱格式不正确"))
            }
        }else{
            cb(new Error('请输入邮箱'))
        }
    }
    let validateMobile = (rules,value,cb)=>{
        if(value){
            let reg =  /^1(3|4|5|6|7|8|9)\d{9}$/
            if(reg.test(value)){
                cb()
            }else{
                cb(new Error("手机格式不正确"))
            }
        }else{
            cb(new Error('请输入手机号'))
        }
    }

    export default {
        data() {
            return {
                query: '', // 查询参数
                pagenum:1, // 当前页码
                pagesize:2,  // 每页数量
                userlist:[],  // 用户列表
                total:0,  // 总数量
                addDialogShow:false,   // 增加弹框显示变量
                editDialogShow:false,   // 修改弹框显示变量
                addUserForm:{  // 添加用户表单
                    username:'',
                    password: '',
                    email: '',
                    mobile: ''
                },
                editUserForm:{  // 修改用户表单
                    username:'',
                    email: '',
                    mobile: ''
                },
                addUserFormRules:{  // 添加表单验证对象
                    username:[
                        {required:true, message:"请输入用户名", trigger:"blur"},
                         {min:2,max:8, message:"长度在2-8之间", trigger:"blur"},
                    ],
                    password:[
                        {required:true, message:"请输入密码", trigger:"blur"},
                         {min:2,max:8, message:"长度在2-10之间", trigger:"blur"},
                    ],
                    email:[
                         { validator: validateEmail, trigger: 'blur' }
                    ],
                    mobile:[
                         { validator: validateMobile, trigger: 'blur' }
                    ]
                },
                editUserFormRules:{  // 修改表单验证对象
                    username:[
                        {required:true, message:"请输入用户名", trigger:"blur"},
                         {min:2,max:8, message:"长度在2-8之间", trigger:"blur"},
                    ],
                    email:[
                         { validator: validateEmail, trigger: 'blur' }
                    ],
                    mobile:[
                         { validator: validateMobile, trigger: 'blur' }
                    ]
                },
                setRoleShow:false, // 控制角色授权弹框打开
                userInfo:{},   // 角色授权的用户信息
                rid:'',   // 绑定给下拉的变量
                rolelist: [],  // 角色列表
            }
        },
        created () {
            this.getUserList()
            this.getRoleList()
        },
        methods: {
            // 获取用户列表
            async getUserList() {
                // 请求数据
                let { data:res } = await this.$axios.get("users",{
                    params:{
                        query:this.query,
                        pagenum:this.pagenum,
                        pagesize:this.pagesize
                    }
                })
                // 错误处理
                if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
                // 成功赋值
                this.userlist = res.data.users
                this.total = res.data.total
            },
            // 获取角色列表
            async getRoleList() {
                // 发送请求
                let { data:res } = await this.$axios.get('roles')
                // 错误处理
                if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
                // 赋值数据
                this.rolelist = res.data
            },
            // 修改用户信息
            async editUser(id){
                // 1. 根据ID查询对应数据信息，赋给修改表单
                let { data:res } = await this.$axios.get("users/"+id)
                if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
                this.editUserForm = res.data
                // 2. 打开弹框
                this.editDialogShow = true

            },
            // 删除用户信息
            async delUser(id){
                try {
                    // 确认弹框，确定返回 confirm字段，取消 抛出错误
                    await this.$confirm('确定删除吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                    // 发送请求
                    let { data:res } = await this.$axios.delete('users/'+id)
                    // 错误处理
                    if(res.meta.status !== 200) this.$message.error(res.meta.msg)
                    // 弹框成功提示
                    this.$message.success('删除成功')
                    // 拉取列表
                    // 【坑：】  如果不是第1页，且这个页码只有1条数据，且被删除完了，页码应该退1
                    if(this.pagenum !==1 && this.userlist.length ===1 ){
                        this.pagenum--
                    }
                    this.getUserList()

                } catch (error) {
                    this.$message.info('取消删除')
                }
            },
            // 页码数量变化
            sizeChange(val){
                this.pagesize = val
                this.getUserList()
            },
            // 页码变化
            pageChange(val){
                this.pagenum = val
                this.getUserList()
            },
            // 根据输入框内容去查询数据
            searchQuery(){
                this.pagenum = 1  //页码归1
                this.getUserList()
            },
            // 输入框内容清空
            resetQuery(){
                this.query = ""
                this.pagenum = 1
                this.getUserList()
            },
            // 添加用户提交事件
            addUserSubmit(){
                // 验证表单信息
                this.$refs.addUserForm.validate(async vaild=>{
                    if(!vaild) return
                    // 发送请求
                    let { data:res } = await this.$axios.post("users",this.addUserForm)
                    // 处理错误
                    if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
                    // 提示成功，拉取最新列表
                    this.$message.success("添加成功")
                    this.getUserList()
                    // 关闭弹框
                    this.resetUserForm('addUserForm')
                })
            },
            // 修改用户表单提交事件
            editUserSubmit(){
                //1.验证规则
                this.$refs.editUserForm.validate(async valid=>{
                    if(!valid) return 
                    //2.发送请求
                    let { data:res } = await this.$axios.put('users/'+this.editUserForm.id,this.editUserForm)
                    //3.错误处理
                    if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    //4.成功处理(拉取列表,关闭弹框)
                    this.$message.success("修改成功")
                    this.getUserList()
                    this.editDialogShow = false
                })
            },
            // 重置用户表单  【添加和修改重置方法】
            resetUserForm(ref_name){
                this.$refs[ref_name].resetFields()
                this.addDialogShow = false
                this.editDialogShow = false
            },
            // 修改用户状态
            async changeStatus(id,state){
                let { data:res } = await this.$axios.put(`users/${id}/state/${state}`)
                if(res.meta.status !== 200) return 
                this.$message.success('修改状态成功')
            },
            // 角色授权
            setUserRole(row){
                this.userInfo = row
                this.setRoleShow = true
            },
            // 角色授权提交事件
            async setRoleSubmit(){
                let { data:res } = await this.$axios.put(`users/${this.userInfo.id}/role`,{
                    rid:this.rid
                })
                if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
                this.setRoleShow = false
                this.getUserList()
            }
        },
    }
</script>

<style lang="less" scoped>

</style>